import 'package:flutter/material.dart';

/// 表单验证
/// 1. 创建一个带GlobalKey的Form
/// 2. 添加TextFormField带着验证逻辑
/// 3. 创建一个按钮验证并提交表单

class ValidationFormApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Validation Form Demo',
      theme: ThemeData(primarySwatch: Colors.red),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Validation Form Demo'),
        ),
        body: ValidationFormAppPage(),
      ),
    );
  }
}

class ValidationFormAppPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => ValidationFormAppPageState();
}

class ValidationFormAppPageState extends State<ValidationFormAppPage> {
  // 创建一个全局密钥，该密钥将唯一标识表单窗口小部件并允许我们验证表单
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          // 无法用于验证
          TextField(
            // 修饰
            decoration: InputDecoration(
                // 设置无边框
                border: InputBorder.none,
                hintText: 'Please enter a search term'),
          ),
          TextFormField(
            validator: (value) {
              if (value.isEmpty) {
                return 'Please enter some text.';
              }
            },
            // 修饰
            decoration: InputDecoration(
                // 提示信息
                labelText: 'Enter your username'),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: RaisedButton(
              onPressed: () {
                if (_formKey.currentState.validate()) {
                  Scaffold.of(context).showSnackBar(
                      SnackBar(content: Text('Processing Data.')));
                }
              },
              child: Text('Submit'),
            ),
          )
        ],
      ),
    );
  }
}
